package com.haierCamera.customapplication.ui;

import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.haierCamera.customapplication.ui.user.MineFragment;
import com.haierCamera.customapplication.ui.user.fragment.HZKLUserLoginFragment;
import com.haierCamera.customapplication.ui.user.fragment.HZKLUserNotFragment;

/**
 * @author yawei
 * @data on 2018/7/18 上午9:15
 * @email zyawei@live.com
 */
public class NavigationController {

    private FragmentManager fragmentManager;
    private final int containerId;

    @Inject
    NavigationController(FragmentManager fragmentManager, int containerId) {
        this.fragmentManager = fragmentManager;
        this.containerId = containerId;
    }

    void nvHome() {
        navigationTo(HomeFragment.class);
    }

    void nvMsg() {
        navigationTo(MsgFragment.class);
    }

    void nvSelf() {
        navigationTo(MineFragment.class);
    }

    public void nvNotLogin() {
        navigationTo(HZKLUserNotFragment.class);
    }

    public void nvLogin() {
        navigationTo(HZKLUserLoginFragment.class);
    }

    public int getCurrentFragmentKey() {
        if(Objects.equals(HomeFragment.class,top)){
            return 1;
        }
        else if (Objects.equals(MsgFragment.class, top)) {
            return 2;
        }
        else if (Objects.equals(MineFragment.class, top)) {
            return 3;
        }

        return top.hashCode();
    }

    public void navigationTo(int key) {
        switch (key) {
            case 1:
                navigationTo(HomeFragment.class);
                break;
            case 2:
                navigationTo(MsgFragment.class);
                break;
            case 3:
                navigationTo(MineFragment.class);
                break;
            default:
                break;

        }
    }

    private Class<? extends Fragment> top;

    private void navigationTo(Class<? extends Fragment> claz) {
        top = claz;

        String className = claz.getSimpleName();

        Fragment fragment = fragmentManager.findFragmentByTag(className);
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (fragment == null) {
            try {
                fragment = claz.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
            fragmentTransaction.add(containerId, fragment, className);
        }

        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment f : fragments) {
            if (f != fragment && !f.isHidden()) {
                fragmentTransaction.hide(f);
            }
        }
        fragmentTransaction.show(fragment).commitNowAllowingStateLoss();
    }
}
